package com.my.aslife.gateway.interceptor;


import cn.hutool.json.JSONUtil;
import com.my.aslife.module.common.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class ReFreshTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Integer userId = UserIdThreadLocal.get();
        // 尚未登录
        if (userId == null) {
            return true;
        }
        // 登录就刷新 token
        String tokenKey = RedisConstant.LOGIN_USER_TOKEN + userId;
        String token = stringRedisTemplate.opsForValue().get(tokenKey);
        if (token == null) {
            response.getWriter().write(JSONUtil.toJsonStr(ResponseResult.failed(ErrorCode.TOKEN_REFRESH_ERROR)));
            return false;
        }
        stringRedisTemplate.opsForValue().set(tokenKey, token, RedisConstant.ONE_DAY, TimeUnit.DAYS);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 防止 OOM
        IPThreadLocal.remove();
        UserIdThreadLocal.remove();
        UploadTypeThreadLocal.remove();
        OrderIdThreadLocal.remove();
    }
}
